from datetime import datetime
from uuid import uuid4
from google.appengine.api import channel
from framework.result import Result
import django.utils.simplejson as json

# in memory storage of all games for now
activeGames = {}

class BaseGame:
	def __init__(self, minimumPlayers, maximumPlayers):
		self.id = str(uuid4())
		# a userId -> Player object dictionary
		self.players = {}
		# a userId -> physical location around the table.  Expressed in degrees from due East
		self.playerPositions = {}
		self.minimumPlayers = minimumPlayers
		self.maximumPlayers = maximumPlayers
		self.started = False

	def startGame(self):
		if len(self.players.items()) >= self.minimumPlayers:
			self.started = True
			self.assignPositions()
			return Result(Result.Success)
		else:
			return Result(Result.NotPossible, 'not enough players')

	def assignPositions(self):
		if len(self.players.items()) > 0:
			spacingInDegrees = 360 / len(self.players.items())
			nextPosition = 0
			for id, player in self.players.items():
				self.playerPositions[id] = nextPosition
				nextPosition += spacingInDegrees

	def addPlayer(self, player):
		if not player.id in self.players:
			if len(self.players) < self.maximumPlayers:
				self.players[player.id] = player
				self.players[player.id].channel = channel.create_channel(self.getChannelId(player))
				return Result(Result.Success)
			else:
				return Result(Result.NotPossible, 'too many players')
		else:
			return Result(Result.NotNeeded, 'player already exists')

	def getPlayer(self, id):
		if id in self.players:
			return self.players[id]
		else:
			return None

	def sendPrivateMessage(self, fromPlayer, toPlayer, message):
		if fromPlayer.id in self.players:
			channel.send_message(self.getChannelId(toPlayer), message)
			self.updateLastAction(fromPlayer)
			return Result(Result.Success)
		else:
			return Result(Result.NotPossible, 'unknown player trying to send a message')

	def sendBroadcastMessage(self, fromPlayer, message, sendToSender):
		messageInJson = json.dumps(message)
		if fromPlayer.id in self.players:
			for id, player in self.players.items():
				if sendToSender or id != fromPlayer.id:
					channel.send_message(self.getChannelId(player), messageInJson)
			self.updateLastAction(fromPlayer)
			return Result(Result.Success)
		else:
			return Result(Result.NotPossible, 'unknown player trying to send a message')

	def getChannelId(self, player):
		return self.id + player.id

	def updateLastAction(self, player):
		player.lastAction = datetime.now()
